#include "LoadGameObjects.h"
#include "File.h"
#include "DX11ErrorReport.h"
#include "Factory.h"
#include "Game.h"

GameObject* CreateObject(const std::string& typeName)
{
	return TheGameObjectFactory::Instance()->Create(typeName);
}

bool LoadGameObjects(const std::wstring& filename)
{
	TheGame::Instance()->ClearGameObjects();

	File* file = new File();
	std::wstring error = L"Could not find file" + filename;
	if (!file->OpenRead(filename))
	{
		DX11ErrorMsg(error.c_str(), L"GameObjectFile Load Error" , MB_YESNO);
		return false;
	}

	while(!file->EndOfFile())
	{		
		std::string gameObjectName;
		if (!file->GetString(&gameObjectName))
		{
			if (file->EndOfFile())
			{
				return true;
			}
			DX11ErrorMsg(L"Expected game object name", L"GameObjectFile Load Error", MB_YESNO);
			return false;
		}

		int id = -1;		
		if (!file->GetInteger(&id))
		{
			DX11ErrorMsg(L"Expected game object id", L"GameObjectFile Load Error", MB_YESNO);
			return false;
		}

		GameObject* g = CreateObject(gameObjectName);
		if (!g)
		{
			DX11ErrorMsg(L"No such game object!", L"GameObjectFile Load Error", MB_YESNO);
			return false;
		}

		std::wstring wGameObjectName;
		wGameObjectName.assign(gameObjectName.begin(), gameObjectName.end());

		wGameObjectName = L"Unexpected values" + wGameObjectName;
		if (!g->Load(file))
		{
			DX11ErrorMsg(wGameObjectName.c_str(), L"GameObjectFile Load Error", MB_YESNO);
		}

		TheGame::Instance()->AddGameObject(id, g);
	}

	delete file;
	return true;
}